﻿using DeskRedis.Model;
using ServiceStack.Redis;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace DeskRedis.MyControl.UserControls
{
    /// <summary>
    /// UCRedisValue4List.xaml 的交互逻辑
    /// </summary>
    public partial class UCRedisValue4List : UserControl
    {
        #region 本地组件
        /// <summary>
        /// 数据表格。
        /// </summary>
        private DataGrid dataGrid;
        #endregion


        #region 私有变量
        /// <summary>
        /// 当前从Redis获取的值信息。
        /// </summary>
        private RedisValue currentRedisValue;
        #endregion


        #region 公共属性
        /// <summary>
        /// 数据表格的数据源。
        /// </summary>
        public IEnumerable ItemsSource
        {
            set { this.dataGrid.ItemsSource = value; }
        }
        #endregion


        #region 构造方法
        /// <summary>
        /// 使用默认的参数创建 DeskRedis.Control.UserControls.UCRedisValue4List 的实例。
        /// </summary>
        public UCRedisValue4List()
        {
            InitializeComponent();
        }
        #endregion


        #region 私有方法
        /// <summary>
        /// 更新值。
        /// </summary>
        /// <param name="configId">redis配置id</param>
        /// <param name="key">键。</param>
        /// <param name="dbIndex">数据库索引。</param>
        /// <param name="type">数据类型。</param>
        private void UpdateValue(string configId, string key, int dbIndex, RedisKeyType type)
        {
            RedisValue redisValue = GlobalBusiness.RedisCaches[configId].Get(key, dbIndex);
            redisValue.ConfigId = configId;
            switch (type)
            {
                case RedisKeyType.List:
                    this.Dispatcher.Invoke(() => { this.dataGrid.ItemsSource = redisValue.List; });
                    break;
                case RedisKeyType.Set:
                    this.Dispatcher.Invoke(() => { this.dataGrid.ItemsSource = redisValue.Set; });
                    break;
                case RedisKeyType.SortedSet:
                    this.Dispatcher.Invoke(() => { this.dataGrid.ItemsSource = redisValue.SortedSet; });
                    break;
                case RedisKeyType.Hash:
                    this.Dispatcher.Invoke(() => { this.dataGrid.ItemsSource = redisValue.Hash; });
                    break;
                default:
                    throw new NotSupportedException("不支持的数据类型：" + type);
            }
        }
        #endregion


        #region 公共方法
        /// <summary>
        /// 设置数据表格。
        /// </summary>
        /// <param name="redisValue"></param>
        /// <param name="dataGrid"></param>
        public void SetDataGrid(RedisValue redisValue, DataGrid dataGrid)
        {
            this.currentRedisValue = redisValue;

            this.tbValue.Clear();
            this.tblockSize.Text = "0";
            this.grid.Children.Clear();
            this.dataGrid = dataGrid;
            this.dataGrid.SelectionChanged += this.DataGrid_SelectionChanged;

            this.grid.Children.Add(this.dataGrid);
        }
        #endregion


        #region 本地事件
        /// <summary>
        /// 当数据表格选项变化时发生。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.dataGrid.SelectedItem == null)
            {
                return;
            }

            if (this.dataGrid.SelectedItem is KeyValuePair<string, double>)
            {
                KeyValuePair<string, double> value = (KeyValuePair<string, double>)this.dataGrid.SelectedItem;
                this.tbValue.Text = value.Key;
                this.tblockSize.Text = Encoding.Default.GetByteCount(value.Key).ToString();
                return;
            }
            if (this.dataGrid.SelectedItem is KeyValuePair<string, string>)
            {
                KeyValuePair<string, string> value = (KeyValuePair<string, string>)this.dataGrid.SelectedItem;
                this.tbValue.Text = value.Key;
                this.tblockSize.Text = Encoding.Default.GetByteCount(value.Key).ToString();
                return;
            }
            if (this.dataGrid.SelectedItem is string)
            {
                string str = this.dataGrid.SelectedItem.ToString();
                this.tbValue.Text = str;
                this.tblockSize.Text = Encoding.Default.GetByteCount(str).ToString();
                return;
            }
        }

        /// <summary>
        /// 当鼠标点击“插入”按钮时发生。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnInsertOne_Click(object sender, RoutedEventArgs e)
        {
            WinInsertValue win = new WinInsertValue(this.currentRedisValue.ConfigId,
                this.currentRedisValue.DBIndex, this.currentRedisValue.Key, this.currentRedisValue.Type);
            win.OnValueInserted += (_configId, _dbIndex, _key, _type) =>
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        this.UpdateValue(_configId, _key, _dbIndex, _type);
                    }
                    catch (Exception ex)
                    {
                        this.Dispatcher.Invoke(() => { MessageBox.Show(ex.Message); });
                    }
                });

            };
            win.ShowDialog();
        }

        /// <summary>
        /// 当鼠标点击“删除行”按钮时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteOne_Click(object sender, RoutedEventArgs e)
        {
            if (this.dataGrid.SelectedItem == null)
            {
                MessageBox.Show("请选择要删除的项！");
                return;
            }

            Task.Factory.StartNew(() =>
            {
                try
                {
                    switch (this.currentRedisValue.Type)
                    {
                        case RedisKeyType.List:
                            {
                                List<string> list = this.dataGrid.ItemsSource as List<string>;
                                this.Dispatcher.Invoke(() =>
                                {
                                    list.RemoveAt(this.dataGrid.SelectedIndex);
                                });

                                GlobalBusiness.RedisCaches[this.currentRedisValue.ConfigId]
                                              .RemoveListItem(this.currentRedisValue.Key, this.currentRedisValue.DBIndex);
                                GlobalBusiness.RedisCaches[this.currentRedisValue.ConfigId]
                                              .AddRangeList(this.currentRedisValue.Key, list, this.currentRedisValue.DBIndex);
                            }
                            break;
                        case RedisKeyType.Set:
                            {
                                string item = null;
                                this.Dispatcher.Invoke(() => { item = this.dataGrid.SelectedItem.ToString(); });
                                GlobalBusiness.RedisCaches[this.currentRedisValue.ConfigId]
                                              .RemoveSetItem(this.currentRedisValue.Key, item, this.currentRedisValue.DBIndex);
                            }
                            break;
                        case RedisKeyType.SortedSet:
                            {
                                KeyValuePair<string, double> item = new KeyValuePair<string, double>();
                                this.Dispatcher.Invoke(() =>
                                {
                                    item = (KeyValuePair<string, double>)this.dataGrid.SelectedItem;
                                });
                                GlobalBusiness.RedisCaches[this.currentRedisValue.ConfigId]
                                              .RemoveSortedSetItem(this.currentRedisValue.Key, item.Key, this.currentRedisValue.DBIndex);
                            }
                            break;
                        case RedisKeyType.Hash:
                            {
                                KeyValuePair<string, string> item = new KeyValuePair<string, string>();
                                this.Dispatcher.Invoke(() =>
                                {
                                    item = (KeyValuePair<string, string>)this.dataGrid.SelectedItem;
                                });
                                GlobalBusiness.RedisCaches[this.currentRedisValue.ConfigId]
                                              .RemoveHashItem(this.currentRedisValue.Key, item.Key, this.currentRedisValue.DBIndex);
                            }
                            break;
                        default:
                            break;
                    }
                    this.UpdateValue(this.currentRedisValue.ConfigId, this.currentRedisValue.Key,
                                    this.currentRedisValue.DBIndex, this.currentRedisValue.Type);
                    this.Dispatcher.Invoke(() => { this.tbValue.Clear(); });
                }
                catch (Exception ex)
                {
                    this.Dispatcher.Invoke(() => { MessageBox.Show("删除出错！" + ex.Message); });
                }
            });
        }
        #endregion


    }
}
